
local socket = require "simplesocket"
local proto = require("proto_json")

local message = {}
local command = {}

local var = {}

local function print_t(t,level)
	level = level or 0
	local tab = string.rep("+",level)
	local tab_cont = string.rep("-",level+1)
	print(tab .. "{")
	for key,value in pairs(t) do
		if type(value) == "table" then
			print(tab_cont .. key .. ":")
			print_t(value,level + 1)
		else
			print(tab_cont .. key .. " : " .. value)
		end
	end
	print(tab .. "}")
end


function message.peer(addr, port)
	var.addr = addr
	var.port = port
end

function message.connect()
	socket.connect(var.addr, var.port)
	socket.isconnect()
end

function message.bind(handler)
	command = handler
end

function message.request(name, args)

	local pkg = proto.create_req(name,args)
	socket.write(pkg)
end

function message.update(ti)
	local msg = socket.read(ti)
	if not msg then
		return false
	end
	local info = proto.unpack(msg:sub(3))
	print_t(info)
	if info.cmd then
		local f = command[info.cmd] 
		if f then
			return f(info.resp)
		else
			log.e(TAg,"not proc to cmd[%s]",cmd)
		end
	else
		log.e(TAG,"not cmd data:",data)
	end

	return true
end

return message
